package com.xtgg.baby;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.device.TextInputActivity;
import com.xtgg.login.LoginActivity;
import com.xtgg.main.DistributeActivity;
import com.xtgg.main.MainPageActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class DeviceInfoActivity extends BaseActivity implements OnClickListener {
	JSONObject mInfo;
	JSONObject mBaby;
	boolean mIsConnect = false;
	BleReceiver mReceiver;
	BluetoothGatt mBluetoothGatt;
	
	public class BleReceiver extends BroadcastReceiver
	{
		@SuppressLint("NewApi")
		public void onReceive(Context paramContext, Intent paramIntent)
	    {
			if (paramIntent.getAction().equals("com.fb.ble.action.device_connect"))
			{
				disMissDailog();
				if(paramIntent.getStringExtra("connect").equals("1")) mIsConnect = true;
				else mIsConnect = false;
				changeStatus();
				
				List<BluetoothGatt> list = ((DemoApp)getApplicationContext()).deviceInfo;
				int size = list.size();
				for(int j = 0; j < size; j++)
				{
					if(list.get(j).getDevice().getAddress().equals(mInfo.getString("andriod_code")))
					{
						mBluetoothGatt = list.get(j);
						break;
					}
				}
				
				if(mTimer != null)
				{
					mTimer.cancel();
					mTimer = null;
				}
			}
	    }
	}
	
	Timer mTimer = null;
	void startTimer()
	{
		if(mTimer != null)
		{
			mTimer.cancel();
			mTimer = null;
		}
		
		final Handler handle = new Handler()
		{
			public void handleMessage(Message msg)
			{
				disMissDailog();
				ToastUtil.showToastWithAlertPic("无法找到设备");
			}
		};
		
		mTimer = new Timer();
		mTimer.schedule(new TimerTask()
		{
			@Override
			public void run() {
				handle.sendEmptyMessage(0);
			}
		}, 10000);
	}

	protected void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_info);

		mReceiver = new BleReceiver();
		IntentFilter localIntentFilter = new IntentFilter();
	    localIntentFilter.addAction("com.fb.ble.action.device_connect");
	    registerReceiver(mReceiver, localIntentFilter);
		
		((TextView) findViewById(R.id.center)).setText("设备管理");
		mInfo = JSON.parseObject(getIntent().getStringExtra("info"));
		mBaby = JSON.parseObject(getIntent().getStringExtra("baby"));

		((TextView) findViewById(R.id.value1)).setText(mInfo
				.getString("d_nickname"));

		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.action0).setOnClickListener(this);
		findViewById(R.id.action1).setOnClickListener(this);
		findViewById(R.id.action2).setOnClickListener(this);
		findViewById(R.id.action3).setOnClickListener(this);
		findViewById(R.id.unbund).setOnClickListener(this);
		
		List<BluetoothGatt> list = ((DemoApp)getApplicationContext()).deviceInfo;
		int size = list.size();
		for(int j = 0; j < size; j++)
		{
			if(list.get(j).getDevice().getAddress().equals(mInfo.getString("andriod_code")))
			{
				mBluetoothGatt = list.get(j);
				mIsConnect = true;
				break;
			}
		}
		
		changeStatus();
	}
	
	void changeStatus()
	{
		if(mIsConnect)
		{
			findViewById(R.id.action1).setVisibility(View.GONE);
			findViewById(R.id.line).setVisibility(View.GONE);
			findViewById(R.id.value4).setVisibility(View.GONE);
			((TextView)findViewById(R.id.label)).setText("断开设备");
		}
		else
		{
			findViewById(R.id.action1).setVisibility(View.VISIBLE);
			findViewById(R.id.line).setVisibility(View.VISIBLE);
			findViewById(R.id.value4).setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.label)).setText("连接设备");
		}

		((TextView)findViewById(R.id.value10)).setText(mInfo.getString("power") + "%");
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		if (resultCode == RESULT_OK) {
			if (requestCode == 11) {
				String babyName = data.getStringExtra("content");
				((TextView) findViewById(R.id.value1)).setText(babyName);
				return;
			} 
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.right:
			BluetoothAdapter.getDefaultAdapter().enable();
			startActivity(new Intent(this,DeviceSearchActivity.class));
			break;

		case R.id.action3:
		{
			Intent intent = new Intent(this, TextInputActivity.class);
			intent.putExtra("title", "设备昵称");
			intent.putExtra("content", ((TextView) findViewById(R.id.value1)).getText().toString());
			intent.putExtra("deviceid", mInfo.getString("deviceid"));
			startActivityForResult(intent, 11);
		}
			break;
			
		case R.id.action0:
		{
			Intent intent = new Intent(this,VetifyCodeActivity.class);
			intent.putExtra("password", mInfo.getString("password"));
			startActivity(intent);
		}
			break;

		case R.id.action1: 
		{
			Intent intent = new Intent(this,DistributeActivity.class);
			intent.putExtra("baby", getIntent().getStringExtra("baby"));
			startActivity(intent);
			break;
		}
		
		case R.id.action2: 
			if(mIsConnect)
			{
				showWaiting("正在连接设备...");
				mBluetoothGatt.disconnect();
				startTimer();
			}
			else
			{
				try{
					if(!BluetoothAdapter.getDefaultAdapter().isEnabled())
					{
						BluetoothAdapter.getDefaultAdapter().enable();
					}
					
					String andriod_code = mInfo.getString("andriod_code");
					if(andriod_code == null || andriod_code.length() == 0)
					{
						showQuerySearch();
					}
					else
					{
						BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
								.getRemoteDevice(andriod_code);
						localBluetoothDevice.connectGatt(DeviceInfoActivity.this, false, ((DemoApp)getApplicationContext()).mGattCallback);
						showWaiting("正在连接设备...");
						startTimer();
					}
				}
				catch(Exception e)
				{
					ToastUtil.showToastWithAlertPic("连接失败");
				}
			}
			break;

		case R.id.unbund:
			showQuery();
			break;
		}
	}
	
	void showQuerySearch() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						startActivity(new Intent(DeviceInfoActivity.this,DeviceSearchActivity.class));
					}
				});
		((TextView)mDialog.findViewById(R.id.content)).setText("该设备未与该手机配对，是否扫描连接？");
		mDialog.show();
	}

	void showQuery() {
		final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						sendHttpRequest("9");
					}
				});
		((TextView)mDialog.findViewById(R.id.content)).setText("是否解除该绑定设备？");
		mDialog.show();
	}
	
	private void sendHttpRequest(String type) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					showToast("设备解除绑定成功");

					List<Activity> list = ((DemoApp) getApplicationContext())
							.getActivityList();
					BabyListActivity act = (BabyListActivity) list.get(list
							.size() - 2);
					act.reloadData();
					finish();
				} 
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "operateDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("deviceid", mInfo.getString("deviceid"));
		params.put("childid", mBaby.getString("childid"));
		params.put("type", type);
		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}
}
